import { useEffect, useRef, useState, useCallback } from 'react';
import { Edit3 } from 'lucide-react';
import './Prompt.css';

/**
 * Prompt 输入对话框组件
 * @param {string} title - 标题
 * @param {string} message - 提示消息
 * @param {string} defaultValue - 默认值
 * @param {string} placeholder - 占位符
 * @param {string} type - 输入框类型（text, password等）
 * @param {string} confirmText - 确认按钮文字
 * @param {string} cancelText - 取消按钮文字
 * @param {function} onConfirm - 确认回调，参数为输入值
 * @param {function} onCancel - 取消回调
 */
export const Prompt = ({
  title = '输入',
  message,
  defaultValue = '',
  placeholder = '',
  type = 'text',
  confirmText = '确认',
  cancelText = '取消',
  onConfirm,
  onCancel
}) => {
  const modalRef = useRef(null);
  const inputRef = useRef(null);
  const [value, setValue] = useState(defaultValue);

  const handleConfirm = useCallback(() => {
    if (value.trim()) {
      onConfirm?.(value.trim());
    }
  }, [value, onConfirm]);

  // 只在组件挂载时聚焦和选中文本
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
      // 只在有默认值时才选中文本
      if (defaultValue) {
        inputRef.current.select();
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // 空依赖数组，只在挂载时执行一次

  // 处理键盘和点击事件
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape') {
        onCancel?.();
      } else if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        handleConfirm();
      }
    };

    const handleClickOutside = (e) => {
      if (modalRef.current && !modalRef.current.contains(e.target)) {
        onCancel?.();
      }
    };

    document.addEventListener('keydown', handleEscape);
    document.addEventListener('mousedown', handleClickOutside);

    return () => {
      document.removeEventListener('keydown', handleEscape);
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [onCancel, handleConfirm]);

  return (
    <div className="prompt-overlay">
      <div ref={modalRef} className="prompt-modal">
        <div className="prompt-icon">
          <Edit3 size={32} strokeWidth={2} />
        </div>
        <div className="prompt-content">
          <h3 className="prompt-title">{title}</h3>
          {message && <p className="prompt-message">{message}</p>}
          <input
            ref={inputRef}
            type={type}
            className="prompt-input"
            value={value}
            onChange={(e) => setValue(e.target.value)}
            placeholder={placeholder}
          />
        </div>
        <div className="prompt-actions">
          <button 
            className="prompt-btn prompt-btn-cancel"
            onClick={onCancel}
          >
            {cancelText}
          </button>
          <button 
            className="prompt-btn prompt-btn-confirm"
            onClick={handleConfirm}
            disabled={!value.trim()}
          >
            {confirmText}
          </button>
        </div>
      </div>
    </div>
  );
};

